﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;

namespace JNPF.IMServe
{
    /// <summary>
    /// 全局消息 - APP端
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018.9.17
    /// </summary>
    public class WebSocketGlobal
    {
        /// <summary>
        /// 静态实例 
        /// </summary>
        public static WebSocketGlobal Instance
        {
            get { return new WebSocketGlobal(); }
        }
        /// <summary>
        /// 发送消息（IM）
        /// </summary>
        /// <param name="tenantId">tenantId</param>
        /// <param name="userId">userId</param>
        /// <param name="toUserId">接收者Id</param>
        /// <param name="messageContent">消息内容</param>
        /// <param name="messageType">消息类型：text/voice/image</param>
        public void SendMessage(string tenantId, string userId, string toUserId, string messageContent, string messageType)
        {
            lock (OnlineUserProvider.locker)
            {
                var onlineUser = OnlineUserProvider.OnlineUserList.FirstOrDefault(q => q.TenantId == tenantId && q.UserId == userId && q.IsMobileDevice == true);
                var onlineToUser = OnlineUserProvider.OnlineUserList.FirstOrDefault(q => q.TenantId == tenantId && q.UserId == toUserId && q.IsMobileDevice == true);
                if (onlineUser != null)
                {
                    SendAsync(onlineUser.WebSocket, JsonConvert.SerializeObject(new { method = "sendMessage", onlineUser.UserId, toUserId, messageType, toMessage = messageContent, dateTime = DateTime.Now }));
                }
                if (onlineToUser != null)
                {
                    SendAsync(onlineToUser.WebSocket, JsonConvert.SerializeObject(new { method = "receiveMessage", formUserId = userId, messageType, formMessage = messageContent, dateTime = DateTime.Now }));
                }
            }
        }
        /// <summary>
        /// 在线（IM）
        /// </summary>
        /// <param name="tenantId">tenantId</param>
        /// <param name="userId">用户Id</param>
        public void Online(string tenantId, string userId)
        {
            lock (OnlineUserProvider.locker)
            {
                var onlineUserList = OnlineUserProvider.OnlineUserList.FindAll(q => q.TenantId == tenantId && q.IsMobileDevice == true);
                foreach (var onlineUser in onlineUserList)
                {
                    SendAsync(onlineUser.WebSocket, JsonConvert.SerializeObject(new { method = "online", userId }));
                }
            }
        }
        /// <summary>
        /// 离线（IM）
        /// </summary>
        /// <param name="tenantId">tenantId</param>
        /// <param name="userId">用户Id</param>
        public void Offline(string tenantId, string userId)
        {
            lock (OnlineUserProvider.locker)
            {
                var onlineUserList = OnlineUserProvider.OnlineUserList.FindAll(q => q.TenantId == tenantId && q.IsMobileDevice == true);
                foreach (var onlineUser in onlineUserList)
                {
                    SendAsync(onlineUser.WebSocket, JsonConvert.SerializeObject(new { method = "offline", userId }));
                }
            }
        }
        private static void SendAsync(WebSocket socket, string message)
        {
            socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text, true, CancellationToken.None);
        }
    }
}
